package com.jd.sunny.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.apache.log4j.Logger;

/**
 * @author :Sun Lin
 * @Description: FileUtil 目录请一律以"/"结尾  (完成)
 * @date :2012-9-12
 * @since:1.0.0
 */

//文件不存在也可以创建成功File对象

public class FileUtil {

    private static Logger logger = LogUtil.getLogger();

    /**
     * 测试工具类
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

//		System.out.println(FileUtil.generateFilename("C:/ext/sunlin.jpg"));  
//		FileUtil.writeFile("G:/download/1.txt", "sunlin"); 
//		FileUtil.deleteFile(new File("G:/download/sunlin/"));
//		logger.info(FileUtil.readFile("G:/download/1.jpg"));
        //复制文件测试(通过)
//		FileUtil.copyFile("G:/download/1/2.jpg", "G:/download/2/");

//		FileUtil.copyFiles("G:/download/1/", "G:/download/2/");
//        FileUtil.compressFiles("G:/download/1", "G:/download/1.zip");
    }

    /**
     * 获取当前工作目录
     *
     * @return
     */
    public static String getCurrentDirectory() {
        return System.getProperty("user.dir");
    }

    /**
     * 根据new File得到当前目录
     *
     * @return
     */
    public static String getCurrentDirectoryByFile() {
        File file = new File("");
        return file.getAbsolutePath();
    }

    public static String generateFilename(String originalFilename) {
        String extensionName = "";
        String filename = "";

        if (originalFilename == null || originalFilename.length() <= 0) {
            return filename;
        }
        int lastIndex = originalFilename.lastIndexOf(".");
        if (lastIndex != -1) {
            extensionName = originalFilename.substring(lastIndex);
            filename = UuidUtil.generateUuid() + extensionName;
        }
        return filename;


    }

    /**
     * 读取文件
     *
     * @param filename
     * @return
     */
    public static String readFile(String filename) {
        StringBuffer stringBuffer = new StringBuffer();

        File file = new File(filename);
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String tempContentString = "";
            while ((tempContentString = bufferedReader.readLine()) != null) {
                stringBuffer.append(tempContentString);
            }
        } catch (FileNotFoundException e) {
            logger.info(e.getStackTrace());
        } catch (IOException e) {
            logger.info(e.getStackTrace());
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 向文件输出字符串
     *
     * @param file
     * @param s
     * @return
     * @throws IOException
     */
    public static boolean writeString(File file, String s) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        byte[] b = s.getBytes();
        fos.write(b);
        fos.flush();
        fos.close();
        return false;
    }

    /**
     * 向文件写数据
     *
     * @param filename
     * @param data
     * @return
     */
    public static boolean writeFile(String filename, String data) {
        FileOutputStream fileOutputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            fileOutputStream = new FileOutputStream(new File(filename));
            outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
            outputStreamWriter.write(data);
            outputStreamWriter.flush();
            return true;
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (outputStreamWriter != null) {
                    outputStreamWriter.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 复制文件
     *
     * @param source
     * @param target ，必须为文件夹，以"/"结尾
     * @return
     * @throws IOException
     */
    public static boolean copyFile(String source, String target) throws IOException {
        File sourceFile = new File(source);
        File targetFileDirectory = new File(target);
        File targetFile = new File(target + "/" + sourceFile.getName());

        //如果目标不存在需要创建目录
        if (!targetFileDirectory.exists()) {
            targetFileDirectory.mkdirs();
            logger.info("创建文件夹：" + targetFileDirectory.getAbsoluteFile());
        }

        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
            logger.info("复制文件开始...");
            int r = -1;
            while ((r = bufferedInputStream.read()) != -1) {
                bufferedOutputStream.write((byte) r);
            }
        } catch (FileNotFoundException e) {
            logger.info("复制文件失败");
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            logger.info("复制文件失败");
            e.printStackTrace();
            return false;
        } finally {
            try {
                bufferedOutputStream.flush();
                bufferedInputStream.close();
                bufferedOutputStream.close();
            } catch (IOException e) {
                logger.info("复制文件失败");
                e.printStackTrace();
                return false;
            }
        }
        logger.info("复制文件：" + source + " 至  " + target);
        logger.info("复制文件完成");
        return true;
    }


    /**
     * 复制文件或这文件夹
     *
     * @param source 可以是文件或者目录，目录请以"/结尾"
     * @param target 必须是目录
     * @return
     * @throws IOException
     */
    public static boolean copyFiles(String source, String target) throws IOException {
        File sourceFile = new File(source);
        File targetFile = new File(target);

        //如果存在并且不是文件夹，直接返回false
        if (targetFile.exists() && !targetFile.isDirectory()) {
            return false;
        }

        if (sourceFile.isFile()) {
            //是文件，就复制,相当于拷贝文件
            copyFile(source, target);
        } else if (sourceFile.isDirectory()) {
            logger.info("复制文件夹：" + sourceFile.getAbsolutePath() + "-->" + targetFile.getAbsolutePath());
            File[] childFiles = sourceFile.listFiles();
            for (File tempFile : childFiles) {
                if (tempFile.isFile()) {
                    //是文件
                    copyFiles(tempFile.getAbsolutePath(), targetFile.getAbsolutePath());
                } else if (tempFile.isDirectory()) {
                    //是文件夹
                    copyFiles(tempFile.getAbsolutePath(), targetFile.getAbsolutePath() + "/" + tempFile.getName());
                }
            }
        }
        return true;
    }

    /**
     * 删除文件或者目录
     *
     * @param file
     * @return
     */
    public static boolean deleteFile(File file) {
        if (file.exists() && file.isDirectory()) {
            File[] childFiles = file.listFiles();
            for (File tempFile : childFiles) {
                deleteFile(tempFile);
            }
            file.delete();
            logger.info("删除文件-->" + file.getAbsolutePath());
        } else if (file.exists() && file.isFile()) {
            file.delete();
            logger.info("删除文件-->" + file.getAbsolutePath());
        } else if (!file.exists()) {
            return false;
        }
        return true;
    }

//    /**
//     * 压缩文件
//     *
//     * @param inputFilePath  文件
//     * @param outputFilePath 输出文件完整路径,例如：G:/download/2/1.zip，最后必须有文件名和压缩的格式
//     * @return
//     * @throws IOException
//     */
//    public static boolean compressFile(String inputFilePath, String outputFilePath) {
//        File inputFile = new File(inputFilePath);
//        //创建ZipEntry
//        ZipEntry zipEntry = new ZipEntry(inputFile.getName());
//        //创建输入输出缓冲流
//        BufferedInputStream bufferedInputStream;
//        try {
//            bufferedInputStream = new BufferedInputStream(new FileInputStream(inputFile));
//            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFilePath));
//            //创建ZipOutputStream输出流
//            ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
//            zipOutputStream.putNextEntry(zipEntry);
//            int content;
//            while ((content = bufferedInputStream.read()) != -1) {
//                zipOutputStream.write(content);
//            }
//            zipOutputStream.flush();
//            zipOutputStream.close();
//        } catch (FileNotFoundException e) {
//            logger.info("压缩文件失败");
//            e.printStackTrace();
//            return false;
//        } catch (IOException e) {
//            logger.info("压缩文件失败");
//            e.printStackTrace();
//            return false;
//        }
//        return true;
//    }
//
//    /**
//     * 压缩文件
//     *
//     * @param inputFilePath  原文件或者目录
//     * @param outputFilePath 输出文件完整路径,例如：G:/download/2/1.zip，最后必须有文件名和压缩的格式
//     * @return
//     * @throws Exception
//     */
//    public static boolean compressFiles(String inputFilePath, String outputFilePath) throws Exception {
//        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFilePath));
//        ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
//        zipOutputStream.setEncoding("GB2312");
//        logger.info("压缩开始");
//        boolean flag = compressFiles(inputFilePath, outputFilePath, "", zipOutputStream);
//        zipOutputStream.flush();
//        zipOutputStream.close();
//        logger.info("压缩完成 ");
//        return flag;
//    }
//
//    private static boolean compressFiles(String inputFilePath, String outputFilePath, String base, ZipOutputStream zipOutputStream) {
//        File inputFile = new File(inputFilePath);
//        try {
//            if (inputFile.isDirectory()) {
//                File[] childFiles = inputFile.listFiles();
//                zipOutputStream.putNextEntry(new ZipEntry(base + "/"));
//                base = base.length() == 0 ? "" : base + "/";
//                for (File tempFile : childFiles) {
//                    compressFiles(tempFile.getAbsolutePath(), outputFilePath, base + tempFile.getName(), zipOutputStream);
//                }
//            } else if (inputFile.isFile()) {
//                //创建ZipEntry
//                zipOutputStream.putNextEntry(new ZipEntry(base));
//                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(inputFile));
//                int content;
//                while ((content = bufferedInputStream.read()) != -1) {
//                    zipOutputStream.write(content);
//                }
//                zipOutputStream.flush();
//                zipOutputStream.closeEntry();
//                bufferedInputStream.close();
//            }
//        } catch (IOException e) {
//            logger.info("压缩文件失败");
//            e.printStackTrace();
//            return false;
//        }
//        return true;
//    }

}
